// 社交分享页面 - 完整版本
const app = getApp();

Page({
  data: {
    currentTab: 'all',
    tabs: [
      { id: 'all', name: '全部' },
      { id: 'experience', name: '经验' },
      { id: 'question', name: '问题' },
      { id: 'achievement', name: '成果' }
    ],
    shares: [],
    loading: false,
    hasMore: true,
    currentPage: 1,
    pageSize: 10
  },

  // 统一图片 URL 构造（最小规则）
  getImageUrl(imagePath) {
    const { buildMediaUrl } = require('../../utils/media');
    return buildMediaUrl(imagePath);
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前';
    }
    // 小于1天
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前';
    }
    // 超过1天
    return date.toLocaleDateString('zh-CN');
  },

  onLoad() {
    console.log('社交分享页面加载');
    console.log('apiBaseUrl:', app.globalData.apiBaseUrl);
    console.log('token:', app.globalData.token ? '已登录' : '未登录');
    console.log('完整token:', app.globalData.token);
    console.log('userInfo:', app.globalData.userInfo);
    
    // 检查本地存储的登录状态
    const localToken = wx.getStorageSync('token');
    const localUserInfo = wx.getStorageSync('userInfo');
    
    if (localToken && !app.globalData.token) {
      app.globalData.token = localToken;
      app.globalData.userInfo = localUserInfo;
      console.log('从本地存储恢复登录状态');
    }
    
    // 直接加载真实数据
    this.loadShares();
  },

  onShow() {
    console.log('社交分享页面显示');
  },

  onPullDownRefresh() {
    this.refreshData();
    wx.stopPullDownRefresh();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadShares();
    }
  },

  // 刷新数据
  refreshData() {
    console.log('刷新数据');
    this.setData({
      shares: [],
      currentPage: 1,
      hasMore: true,
      loading: true
    });
    this.loadShares(1);
  },

  // 加载分享列表
  async loadShares(page = null, shareType = null) {
    // 检查是否正在加载，避免重复请求
    if (this.data.loading && page === null) return;
    if (!this.data.hasMore && page === null) return;

    this.setData({ loading: true });
    console.log('开始加载分享列表...', { page, shareType });

    try {
      const currentPage = page || this.data.currentPage;
      const currentTab = shareType || this.data.currentTab;
      const requestData = {
        page: currentPage,
        per_page: this.data.pageSize
      };

      if (currentTab !== 'all') {
        requestData.share_type = currentTab;
      }

      console.log('请求参数:', requestData);

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/get-shares`,
          method: 'GET',
          data: requestData,
          header: {
            'Content-Type': 'application/json',
            'Authorization': app.globalData.token ? `Bearer ${app.globalData.token}` : ''
          },
          success: resolve,
          fail: reject
        });
      });

      console.log('API响应状态:', res.statusCode);
      console.log('API响应数据:', res.data);

      if (res.statusCode === 200) {
        if (res.data.success) {
          const { mapMediaUrls } = require('../../utils/media');
          let newShares = (res.data.data.shares || []).map(s => {
            const mapped = mapMediaUrls(s.image_urls);
            return {
              ...s,
              image_urls: mapped,
              // 兼容若模板可能使用 images 字段
              images: mapped
            };
          });
          console.log('映射后的分享图片数组调试:', newShares.map(x => ({id:x.id, image_urls:x.image_urls}))); 
          
          // 如果是第一页或者换了标签，重置列表
          const isFirstPage = currentPage === 1;
          const currentShares = isFirstPage ? [] : this.data.shares;
          
          this.setData({
            shares: [...currentShares, ...newShares],
            currentPage: isFirstPage ? 2 : currentPage + 1,
            hasMore: newShares.length === this.data.pageSize
          });

          // 在本地开发(HTTP)场景：将不安全 http 图片下载为本地临时文件以规避组件直接渲染限制
          
          console.log('分享列表加载成功，数量:', newShares.length);
          console.log('当前页面shares数据:', this.data.shares);
          
          // 如果没有数据，显示空状态
          if (this.data.shares.length === 0) {
            this.showEmptyState('暂无分享内容，快来发布第一个分享吧！');
          }
        } else {
          console.error('API返回失败:', res.data.message);
          this.showEmptyState('API返回失败: ' + res.data.message);
        }
      } else if (res.statusCode === 401) {
        console.log('需要登录');
        this.showEmptyState('请先登录查看分享内容');
      } else {
        console.error('API状态异常:', res.statusCode, res.data);
        this.showEmptyState('服务器响应异常');
      }
    } catch (error) {
      console.error('加载分享失败:', error);
      this.showEmptyState('网络连接失败，请检查服务器状态');
    } finally {
      this.setData({ loading: false });
    }
  },


  // 图片预览（列表）
  onPreviewImage(e){
    const shareIndex = e.currentTarget.dataset.shareIndex;
    const imgIndex = e.currentTarget.dataset.imgIndex;
    const share = this.data.shares[shareIndex];
    if(!share || !Array.isArray(share.image_urls)) return;
    wx.previewImage({
      current: share.image_urls[imgIndex],
      urls: share.image_urls
    });
  },

  // 显示空状态
  showEmptyState(message) {
    this.setData({
      shares: [],
      hasMore: false,
      emptyMessage: message || '暂无分享内容'
    });
  },

  // 标签页切换
  onTabChange(e) {
    const tabId = e.currentTarget.dataset.id;
    console.log('切换标签页:', tabId);
    
    if (tabId === this.data.currentTab) return;

    this.setData({ 
      currentTab: tabId,
      loading: true,
      shares: [],
      currentPage: 1,
      hasMore: true
    });
    
    // 直接加载对应标签的数据
    this.loadShares(1, tabId === 'all' ? null : tabId);
  },

  // 创建分享
  onCreateShare() {
    console.log('点击创建分享按钮');
    
    // 检查登录状态
    if (!app.globalData.token) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再创建分享',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login?redirect=' + encodeURIComponent('/pages/social/social')
            });
          }
        }
      });
      return;
    }

    wx.navigateTo({
      url: '/pages/social/create/create',
      fail: (error) => {
        console.error('跳转创建页面失败:', error);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  // 点赞
  async onLike(e) {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
    
    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const shareId = e.currentTarget.dataset.id;
    const shareIndex = e.currentTarget.dataset.index;
    const currentType = this.data.currentType;
    
    if (!shareId) {
      console.error('缺少分享ID');
      return;
    }

    try {
      wx.showLoading({ title: '处理中...' });

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/toggle-like`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${app.globalData.token}`
          },
          data: { share_id: shareId },
          success: resolve,
          fail: reject
        });
      });

      wx.hideLoading();

      if (res.statusCode === 200 && res.data.success) {
        const { is_liked, like_count } = res.data.data;
        
        // 更新页面数据
        const shares = this.data.shares;
        if (shares[shareIndex]) {
          shares[shareIndex].is_liked = is_liked;
          shares[shareIndex].like_count = like_count;
          this.setData({ shares });
        }

        wx.showToast({
          title: is_liked ? '点赞成功' : '取消点赞',
          icon: 'success',
          duration: 1000
        });
      } else {
        throw new Error(res.data.message || '操作失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('点赞失败:', error);
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      });
    }
  },

  // 评论
  onComment(e) {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
    
    const shareId = e.currentTarget.dataset.id;
    const title = e.currentTarget.dataset.title || '分享详情';
    
    if (!shareId) {
      console.error('缺少分享ID');
      return;
    }

    // 跳转到评论页面
    wx.navigateTo({
      url: `/pages/social/comments/comments?shareId=${shareId}&title=${encodeURIComponent(title)}`
    });
  },

  async onFollow(e) {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
    
    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const followingId = e.currentTarget.dataset.userId;
    const shareIndex = e.currentTarget.dataset.index;
    const currentType = this.data.currentType;
    
    if (!followingId) {
      console.error('缺少用户ID');
      return;
    }

    try {
      wx.showLoading({ title: '处理中...' });

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/toggle-follow`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${app.globalData.token}`
          },
          data: { following_id: followingId },
          success: resolve,
          fail: reject
        });
      });

      wx.hideLoading();

      if (res.statusCode === 200 && res.data.success) {
        const { is_following } = res.data.data;
        
        // 更新页面数据
        const shares = this.data.shares;
        if (shares[shareIndex]) {
          shares[shareIndex].is_following = is_following;
          this.setData({ shares });
        }

        wx.showToast({
          title: is_following ? '关注成功' : '取消关注',
          icon: 'success',
          duration: 1000
        });
      } else {
        throw new Error(res.data.message || '操作失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('关注失败:', error);
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      });
    }
  },

  onShare(e) {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
    
    const shareId = e.currentTarget.dataset.id;
    
    // 跳转到详情页面进行分享，提供更完整的分享体验
    wx.navigateTo({
      url: `/pages/social/detail/detail?id=${shareId}&action=share`
    });
  },

  // 记录分享事件
  async recordShareEvent(shareId) {
    if (!app.globalData.token || !shareId) return;
    
    try {
      wx.request({
        url: `${app.globalData.apiBaseUrl}/social/record-share`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${app.globalData.token}`
        },
        data: { share_id: shareId },
        success: (res) => {
          if (res.statusCode === 200 && res.data.success) {
            console.log('分享记录成功');
          }
        }
      });
    } catch (error) {
      console.error('记录分享失败:', error);
    }
  },

  // 用户头像点击
  onUserProfile(e) {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
    console.log('点击用户头像');
    
    wx.showToast({
      title: '用户主页功能开发中',
      icon: 'none'
    });
  },

  // 分享详情
  onShareDetail(e) {
    const shareId = e.currentTarget.dataset.id;
    console.log('点击分享详情，ID:', shareId);
    
    if (!shareId) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/social/detail/detail?id=${shareId}`,
      fail: (err) => {
        console.error('跳转详情页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    try {
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;
      
      const minute = 60 * 1000;
      const hour = minute * 60;
      const day = hour * 24;

      if (diff < minute) {
        return '刚刚';
      } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前';
      } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前';
      } else {
        return Math.floor(diff / day) + '天前';
      }
    } catch (error) {
      console.error('时间格式化失败:', error);
      return '';
    }
  }
});

